#coding=UTF-8
import requests
import json

# 引入自定义的keystone模块
import keystone
keystone_s=keystone.getToken()

#nova(compute)端点地址：
compute_url="http://192.168.100.10:8774/v2.1/servers"
#定义请求头
headers={
    "X-Auth-Token":keystone_s['token'],
    "Content-Type": "application/json"
}

#定义请求主题
body={
	"server": {
		"name": "rustful-api-ok-good-02",
		"imageRef": "dea0112c-cc0c-4194-874d-09c0052e2931",
		"flavorRef": "c8095e4f-9166-481d-aa5c-77b79f78a0b5",
		"networks": [
			{
				"uuid": "9ea4840a-8214-4cda-9c9f-d69e28857820",
				"fixed_ip": "192.168.200.109"
			}
		],
		"metadata": {
			"My Server Name": "Apach"
		},
		"block_device_mapping_v2": [
			{
				"uuid": "dea0112c-cc0c-4194-874d-09c0052e2931",
				"source_type": "image",
				"destination_type": "volume",
				"boot_index": 0,
				"volume_size": "1"
			},
			{
				"source_type": "blank",
				"destination_type": "volume",
				"boot_index": 1,
				"volume_size": "1"
			}
		]
	}
}

#发送请求
req=requests.post(compute_url,headers=headers,data=json.dumps(body))
#格式化打印响应
print(json.dumps(req.json(),sort_keys=True,indent=4))

if req.status_code == 202:
    print("创建成功  server id:"+str(req.json()['server']['id']))
else:
    print("创建失败！")
#
# #循环打印主机列表
# for i in req.json()['servers']:
#     print("server name:",str(i['name']),"id:",str(i['id']))